package com.sys.server.common.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2  // 开启Swagger2
@EnableKnife4j  // 开启knife4j
public class SwaggerConfig {

    /**
     * apiInfo添加API相关信息
     * 通过select函数返回一个ApiSelectorBuilder实例，用来控制哪些接口暴露给Swagger展示
     * 采用指定扫描的包路径来定义指定要建立API的目录
     * @return
     */
    @Bean
    public Docket creatRestApi() {

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 哪些包需要生成接口文档
                .apis(RequestHandlerSelectors.basePackage("com.sys.server.modules.controller"))
                // 匹配哪些请求路径在Swagger中展示
                .paths(PathSelectors.regex("/.*"))
                .build()
                .globalOperationParameters(globalOperationParameters())
                ;
    }

    /**
     * 创建该API的基本信息（这些信息会展示在文档中）
     * 本项目Swagger访问地址：http://localhost:8090/sys/swagger-ui.html
     * @return
     */
    public ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("校企联合项目案例库管理系统 V1.0")
                .description("api文档")
                .version("1.0")
                .build();
    }

    private List<Parameter> globalOperationParameters() {
        ParameterBuilder pars = new ParameterBuilder();
        List<Parameter> parsList = new ArrayList<>();
        pars.name("Authorization").description("").modelRef(new ModelRef("string")).parameterType("header").required(false);
        parsList.add(pars.build());
        return parsList;
    }

}
